package com.ojoin.trade.supplyloan_core.web.service.impl;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ojoin.trade.common.utils.CommonUtils;
import com.ojoin.trade.common.utils.LogUtils;
import com.ojoin.trade.common.utils.TimeUtils;
import com.ojoin.trade.common.utils.json.JSONUtils;
import com.ojoin.trade.common.web.dao.BaseDao;
import com.ojoin.trade.common.web.service.impl.BaseServiceImpl;
import com.ojoin.trade.supplyloan_core.web.dao.TbCatchdataStrategyDao;
import com.ojoin.trade.supplyloan_core.web.domain.TbCatchdataStrategy;
import com.ojoin.trade.supplyloan_core.web.domain.TbCatchdataStrategyProperty;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlLoanStatTotal;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlPlatformInfo;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlPlatformUser;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlStatetaskRunresultvo;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlSupplyInventory;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlSupplyPayment;
import com.ojoin.trade.supplyloan_core.web.service.TbCatchdataStrategyService;
import com.ojoin.trade.supplyloan_core.web.service.TbSlLoanStatTotalService;
import com.ojoin.trade.supplyloan_core.web.service.TbSlPlatformInfoService;
import com.ojoin.trade.supplyloan_core.web.service.TbSlPlatformUserService;
import com.ojoin.trade.supplyloan_core.web.service.TbSlStattaskRunresultService;
import com.ojoin.trade.supplyloan_core.web.service.TbSlSupplyInventoryService;
import com.ojoin.trade.supplyloan_core.web.service.TbSlSupplyPaymentService;

@Service
public class TbCatchdataStrategyServiceImpl extends
		BaseServiceImpl<TbCatchdataStrategy> implements
		TbCatchdataStrategyService {

	private static Logger log = LoggerFactory
			.getLogger(TbCatchdataStrategyServiceImpl.class);

	@Autowired
	private TbCatchdataStrategyDao dao;

	@Autowired
	private TbSlLoanStatTotalService statTotalService;

	@Autowired
	private TbSlStattaskRunresultService runResultService;

	@Autowired
	private TbSlPlatformInfoService platformInfoService;

	@Autowired
	private TbSlSupplyPaymentService paymentService;

	@Autowired
	private TbSlSupplyInventoryService inventoryService;

	@Autowired
	private TbSlPlatformUserService platformUserService;

	@Override
	public void insetr(TbCatchdataStrategy tbCatchdataStrategy) {
		if (null != tbCatchdataStrategy) {
			dao.insert(tbCatchdataStrategy);
		}

	}

	@Override
	protected BaseDao<TbCatchdataStrategy> getBaseDao() {
		return dao;
	}

	@Override
	public TbCatchdataStrategy queryByPlatformUserId(int platformUserId) {
		return dao.queryByPlatformUserId(platformUserId);
	}

	@Override
	public void stat() {
		List<TbSlStatetaskRunresultvo> li = runResultService
				.queryAllSuccessTbSltaskRunresultToday();

		if (null != li && li.size() > 0) {
			for (int i = 0; i < li.size(); i++) {
				TbSlStatetaskRunresultvo tt = li.get(i);
				stat(tt);
			}
		}
	}

	@Override
	public void stat(TbSlStatetaskRunresultvo statetaskRunresul) {

		TbSlPlatformUser user = platformUserService.queryById(statetaskRunresul
				.getIdOfPlatformUser());

		TbCatchdataStrategy ca = queryByPlatformUserId(user.getId());

		stat(user, ca);

	}

	@Override
	public void stat(TbSlPlatformUser user) {

		TbCatchdataStrategy ca = queryByPlatformUserId(user.getId());

		stat(user, ca);

	}

	@Override
	public void stat(TbSlPlatformUser user, TbCatchdataStrategy ca) {

		// 删除今日的全部统计数据
		statTotalService.deleteTbSlLoanTotalByPlatformUserIDAndDate(
				user.getId(), TimeUtils.getCurDate());

		TbSlPlatformInfo info = platformInfoService.queryByName(user
				.getPlatformName());

		LogUtils.info(
				log,
				"平台[%s][%s]",
				info.getPlatformName(),
				info.getPlatformName()
						.equals(TbSlPlatformInfo.SUPPLIER_CAINIAO)
						|| info.getPlatformName().equals(
								TbSlPlatformInfo.THIRDSELLER_TMALL));

		// 插入截止今日的全部统计数据
		TbSlLoanStatTotal total = statTotalService
				.getTbSlLoanStatTotalVoByPlatformUser(user);

		if (info.getPlatformName().equals(TbSlPlatformInfo.SUPPLIER_AMAZON)) {
			statAMAZON(user, ca, total);
		} else if (info.getPlatformName().equals(
				TbSlPlatformInfo.SUPPLIER_SFBEST)) {
			statSUPPLIER_SFBEST(user, ca, total);
		} else if (info.getPlatformName().equals(
				TbSlPlatformInfo.THIRDSELLER_JD)) {
			statTHIRDSELLER_JD(user, ca, total);
		} else if (info.getPlatformName().equals(TbSlPlatformInfo.SUPPLIER_YHD)) {
			statYHD(user, ca, total);
		} else if (info.getPlatformName().equals(
				TbSlPlatformInfo.SUPPLIER_SUNING)) {
			statSUNING(user, ca, total);
		} else if (info.getPlatformName().equals(
				TbSlPlatformInfo.THIRDSELLER_SUNING)) {
			statTHIRD_SUNING(user, ca, total);
		} else if (info.getPlatformName().equals(
				TbSlPlatformInfo.SUPPLIER_TMALL)) {
			statSUPPLIER_TMALL(user, ca, total);
		} else if (info.getPlatformName().equals(
				TbSlPlatformInfo.SUPPLIER_WOMAI)) {
			statSUPPLIER_WOMAI(user, ca, total);
		} else if (info.getPlatformName().equals(TbSlPlatformInfo.SUPPLIER_JD)) {
			statSUPPLIER_JD(user, ca, total);
		} else if (info.getPlatformName().equals(
				TbSlPlatformInfo.SUPPLIER_CAINIAO)
				|| info.getPlatformName().equals(
						TbSlPlatformInfo.THIRDSELLER_TMALL)) {
			statCAINIAO(user, ca, total);
		} else if (info.getPlatformName()
				.equals(TbSlPlatformInfo.SUPPLIER_GOME)) {
			long paymoney = paymentService
					.querySupplysettlementMoneyByRowCreateTimeToday(user
							.getId());
			total.setTotalUnpaySettleorder(paymoney);
		}

		LogUtils.info(log, "-->" + JSONUtils.toJSONString(total));

		statTotalService.insert(total);

	}

	// @Override
	public void statCAINIAO(TbSlPlatformUser user, TbCatchdataStrategy ca,
			TbSlLoanStatTotal total) {

		String time = TimeUtils.getCurDate();

		long inveInMoney = inventoryService
				.queryInventoryInMoneyByRowCreateTime(user.getId(), time, time);

		total.setTotalUnsettleInstoreorder(inveInMoney);

		long settorcheck = paymentService.querySupplysettlementMoney(
				user.getId(), null, null, time, time,
				TbSlSupplyPayment.AVAILABLEBALANCE);

		total.setTotalPaySettleorder(settorcheck);

		LogUtils.info(log, "  %s --> [all store in %s]  + [all unpayment %s] ",
				user.getUsername(), inveInMoney, settorcheck);

	}

	public void statSUNING(TbSlPlatformUser user, TbCatchdataStrategy ca,
			TbSlLoanStatTotal total) {
		
		
		long inveInMoney = inventoryService.queryInventoryInMoney(user.getId());
		long inveOutMoney = inventoryService.queryInventoryOutMoney(user.getId());


		total.setTotalUnsettleInstoreorder(inveInMoney);
		total.setTotalUnenterinRefundorder(inveOutMoney);

		long paymoney = paymentService.querySupplysettlementMoney(user.getId(), TbSlSupplyPayment.COMPLETEPAY);

		/*LogUtils.info(
				log,
				"statSUNING  %s --> [all store in inventoryInStartTime: %s ----inveInMoney:%s ] + [all store out inventoryOutStartTime:%s --- inveOutMoney : %s] - [all payment payStartTime : %s ---paymoney : %s  ] ",
				user.getUsername(),inventoryInStartTime,inveInMoney,inventoryOutStartTime,inveOutMoney,payStartTime,paymoney);
		*/
		
		total.setTotalPaySettleorder(paymoney);

	}
	
	/*@Override
	public void statSUNING(TbSlPlatformUser user, TbCatchdataStrategy ca,
			TbSlLoanStatTotal total) {
		String inventoryInStartTime ;
		String inventoryOutStartTime ;
		String payStartTime ;
		
		TbCatchdataStrategyProperty map ;
	    String inventoryInEndTime = TimeUtils.getCurDate();;
	    String inventoryOutEndTime = TimeUtils.getCurDate();
	    String payEndTime =TimeUtils.getCurDate();
		String data = ca.getSupplementaryData();
		
		if(!CommonUtils.isEmpty(data)){
			map = JSONUtils.parseObject(data, TbCatchdataStrategyProperty.class);
			inventoryInStartTime = CommonUtils.isEmpty(map.getInventoryInStartTime())?TimeUtils.getDateBefore(30*4):map.getInventoryInStartTime();
			inventoryOutStartTime = CommonUtils.isEmpty(map.getInventoryOutStartTime())?TimeUtils.getDateBefore(30*4):map.getInventoryOutStartTime();
			payStartTime = CommonUtils.isEmpty(map.getPayStartTime())?TimeUtils.getDateBefore(30*3):map.getPayStartTime();
			map.setInventoryInStartTime(inventoryInStartTime);
			map.setInventoryOutStartTime(inventoryOutStartTime);
			map.setPayStartTime(payStartTime);
		}else {
			map = new TbCatchdataStrategyProperty();
			inventoryInStartTime = TimeUtils.getDateBefore(30*4);
			inventoryOutStartTime = TimeUtils.getDateBefore(30*4);
			payStartTime = TimeUtils.getDateBefore(30*3);
			map.setInventoryInStartTime(inventoryInStartTime);
			map.setInventoryOutStartTime(inventoryOutStartTime);
			map.setPayStartTime(payStartTime);
			
		}

		ca.setSupplementaryData(JSONUtils.toJSONString(map));
		this.updateById(ca);
		
		long inveInMoney = inventoryService.queryInventoryInMoneyByStoreDate(user.getId(), inventoryInStartTime, inventoryInEndTime);
		long inveOutMoney = inventoryService.queryInventoryOutMoneyByStoreDate(user.getId(), inventoryOutStartTime, inventoryOutEndTime);


		total.setTotalUnsettleInstoreorder(inveInMoney);
		total.setTotalUnenterinRefundorder(inveOutMoney);

		long paymoney = paymentService.querySupplyPaymentMoney(user.getId(), payStartTime, payEndTime);

		LogUtils.info(
				log,
				"statSUNING  %s --> [all store in inventoryInStartTime: %s ----inveInMoney:%s ] + [all store out inventoryOutStartTime:%s --- inveOutMoney : %s] - [all payment payStartTime : %s ---paymoney : %s  ] ",
				user.getUsername(),inventoryInStartTime,inveInMoney,inventoryOutStartTime,inveOutMoney,payStartTime,paymoney);
		
		total.setTotalPaySettleorder(paymoney);

	}*/


	@Override
	public void statAMAZON(TbSlPlatformUser user, TbCatchdataStrategy ca,
			TbSlLoanStatTotal total) {

		String stime = paymentService.getLastsettlementDate(user.getId()).replace("/", "-");
		if (CommonUtils.isEmpty(stime)) {
			stime = paymentService.getLastInsertTime(user.getId());
		}
		String etime = TimeUtils.getCurDate();

		long inveInMoney = inventoryService.queryInventoryInMoneyByStoreDate(
				user.getId(), stime, etime);
		long inveOutMoney = inventoryService.queryInventoryOutMoneyByStoreDate(
				user.getId(), stime, etime);


		long paymoney = paymentService.querySupplysettlementMoney(user.getId());

		total.setTotalUnsettleInstoreorder(inveInMoney);
		total.setTotalUnenterinRefundorder(inveOutMoney);
		total.setTotalUnpaySettleorder(paymoney);

		LogUtils.info(
				log,
				"%s -->  %s-->[ store all in %s ] + [all Unpay] [settlementDate %s]",
				user.getPlatformName(), user.getUsername(), inveInMoney, stime);
		/*
		 * LogUtils.info( log,
		 * "%s -->  %s-->[ store in stime:%s--etime:%s] + [store out stime:%s--etime:%s] + [all Unpay] "
		 * , user.getPlatformName(),user.getUsername(),stime,etime,stime,etime);
		 */

	}

	public static void main(String[] args) {

		System.out.print("2016/2/8".replace("/", "-"));
		
		
		TbSlPlatformUser user = new TbSlPlatformUser();
		user.setPlatformName("ss");
		user.setUsername("aa");
		String stime = "1";
		String etime = "2";

		LogUtils.info(
				log,
				"%s -->  %s-->[ store in stime:%s--etime:%s] + [store out stime:%s--etime:%s] + [all Unpay] ",
				user.getPlatformName(), user.getUsername(), stime, etime,
				stime, etime);
	}

	@Override
	public void statYHD(TbSlPlatformUser user, TbCatchdataStrategy ca,
			TbSlLoanStatTotal total) {
		String stime = paymentService.getLastsettlementDate(user.getId());
		if (CommonUtils.isEmpty(stime)) {
			stime = paymentService.getLastInsertTime(user.getId());
		}
		String etime = TimeUtils.getCurDate();

		List<String> unpayIds = new ArrayList<String>();

		final int CLEARINGSCYCLE = 48;

		final int[] clearingsDay = { 6, 16, 26 };

		long paymoney = 0;
		Map<String, TbSlSupplyPayment> map = paymentService
				.queryByUidAndsettlementState(user.getId(),
						TbSlSupplyPayment.WAITPAY);

		Iterator<Map.Entry<String, TbSlSupplyPayment>> it = map.entrySet()
				.iterator();
		while (it.hasNext()) {
			Map.Entry<String, TbSlSupplyPayment> en = it.next();

			TbSlSupplyPayment tb = en.getValue();

			String strday;
			String needtime;
			try {
				needtime = TimeUtils.getDateAfterDays(tb.getCreateDate(),
						CLEARINGSCYCLE);

				int day = Integer.valueOf(TimeUtils.getCurDay(needtime
						.substring(0, 10)));

				if (clearingsDay[0] <= day && day < clearingsDay[1]) {
					strday = String.valueOf(clearingsDay[1]);
				} else if (clearingsDay[1] <= day && day < clearingsDay[2]) {
					strday = String.valueOf(clearingsDay[2]);
				} else {
					strday = "0" + String.valueOf(clearingsDay[0]);
				}

				needtime = needtime.substring(0, 8) + strday;

				if (TimeUtils.getDateSpaceOfDay(needtime,
						TimeUtils.getCurDate()) <= 0) {
					unpayIds.add(tb.getSettlementId());
					paymoney = paymoney + tb.getAmount();
				}

			} catch (ParseException e) {
				LogUtils.error(log, "时间转化出错" + tb.getCreateDate());
			} catch (Exception e) {
				LogUtils.error(log, "时间转化出错" + tb.getCreateDate());
			}
		}

		long inveInMoney = inventoryService.queryInventoryInMoneyByStoreDate(
				user.getId(), stime, etime);
		long inveOutMoney = inventoryService.queryInventoryOutMoneyByStoreDate(
				user.getId(), stime, etime);

		total.setTotalUnsettleInstoreorder(inveInMoney);
		total.setTotalUnenterinRefundorder(inveOutMoney);
		total.setTotalUnpaySettleorder(paymoney);

		LogUtils.info(
				log,
				"statYHD  %s --> [ store in stime:%s--etime:%s] + [store out stime:%s--etime:%s] + [ Unpay : %s] ",
				user.getUsername(), stime, etime, stime, etime,
				JSONUtils.toJSONString(unpayIds));
	}

	@Override
	public void statTHIRD_SUNING(TbSlPlatformUser user, TbCatchdataStrategy ca,
			TbSlLoanStatTotal total) {

		StringBuffer sb = new StringBuffer();
		String stime = paymentService.getLastsettlementDate(user.getId());
		String etime = TimeUtils.getCurDate();
		long inveInMoney = inventoryService.queryInventoryInMoneyByStoreDate(
				user.getId(), stime, etime);
		long inveOutMoney = inventoryService.queryInventoryOutMoneyByStoreDate(
				user.getId(), stime, etime);

		total.setTotalUnsettleInstoreorder(inveInMoney);
		total.setTotalUnenterinRefundorder(inveOutMoney);

		Set<String> waitpayids = new HashSet<String>();

		List<TbSlSupplyPayment> waitpays = paymentService
				.queryByUidAndCreateDate(user.getId(),
						TimeUtils.getDateBefore(ca.getSettlementInterval()),
						TimeUtils.getCurDate(), TbSlSupplyPayment.WAITPAY);

		List<TbSlSupplyPayment> completepays = paymentService
				.queryByUidAndCreateDate(user.getId(),
						TimeUtils.getDateBefore(ca.getPaymentInterval()),
						TimeUtils.getCurDate(), TbSlSupplyPayment.COMPLETEPAY);

		if (null != waitpays) {
			Iterator<TbSlSupplyPayment> it = waitpays.iterator();
			while (it.hasNext()) {
				TbSlSupplyPayment tbsl = it.next();
				waitpayids.add(tbsl.getSettlementId());
				sb.append("[waitpayid:" + tbsl.getSettlementId() + "---unpay:"
						+ tbsl.getAmount() + "]");
				total.setTotalUnpaySettleorder(total.getTotalUnpaySettleorder()
						+ tbsl.getAmount());

			}

		}

		if (null != completepays) {
			Iterator<TbSlSupplyPayment> it = completepays.iterator();
			while (it.hasNext()) {
				TbSlSupplyPayment tbsl = it.next();
				if (waitpayids.contains(tbsl.getSettlementId())) {
					sb.append("[payid:" + tbsl.getPayId() + "---pay:"
							+ tbsl.getAmount() + "]");
					total.setTotalPaySettleorder(total.getTotalPaySettleorder()
							+ tbsl.getAmount());
				}
			}
		}

		LogUtils.info(
				log,
				"statTHIRD_SUNING  %s --> [ store in stime:%s--etime:%s] + [store out stime:%s--etime:%s] + [ Unpay  %s] ",
				user.getUsername(), stime, etime, stime, etime, sb);

	}

	@Override
	public void statSUPPLIER_SFBEST(TbSlPlatformUser user,
			TbCatchdataStrategy ca, TbSlLoanStatTotal total) {

		String stime = paymentService.getLastsettlementDate(user.getId());
		if (CommonUtils.isEmpty(stime)) {
			stime = paymentService.getLastcreateDate(user.getId());
		}
		String etime = TimeUtils.getCurDate();

		long inveInMoney = inventoryService.queryInventoryInMoneyByStoreDate(
				user.getId(), stime, etime);
		long inveOutMoney = inventoryService.queryInventoryOutMoneyByStoreDate(
				user.getId(), stime, etime);

		long paymoney = paymentService.querySupplysettlementMoney(user.getId());

		total.setTotalUnsettleInstoreorder(inveInMoney);
		total.setTotalUnenterinRefundorder(inveOutMoney);
		total.setTotalUnpaySettleorder(paymoney);

		LogUtils.info(
				log,
				"%s  %s --> [ store in stime:%s--etime:%s] + [store out stime:%s--etime:%s] + [all Unpay] ",
				user.getPlatformName(), user.getUsername(), stime, etime,
				stime, etime);

	}

	@Override
	public void statTHIRDSELLER_JD(TbSlPlatformUser user,
			TbCatchdataStrategy ca, TbSlLoanStatTotal total) {
		String time = TimeUtils.getCurDate();
		long paymoney = paymentService.querySupplysettlementMoney(user.getId(),
				null, null, time, time, TbSlSupplyPayment.WAITPAY);

		long settorcheck = paymentService.querySupplysettlementMoney(
				user.getId(), null, null, time, time,
				TbSlSupplyPayment.CHECKEDPAY);

		long inveInMoney = 0;
		long inveOutMoney = 0;

		if (ca.getInventoryCatchAllOrPart()
				.equals(TbCatchdataStrategy.CatchAll)) {
			inveInMoney = inventoryService.queryInventoryMoneyByRowCreateTime(
					user.getId(), time, time, TbSlSupplyInventory.IN);

			inveOutMoney = inventoryService.queryInventoryMoneyByRowCreateTime(
					user.getId(), time, time, TbSlSupplyInventory.OUT);
		} else {
			inveInMoney = inventoryService.queryInventoryInMoney(user.getId());

			inveOutMoney = inventoryService
					.queryInventoryOutMoney(user.getId());
		}

		total.setTotalUnsettleInstoreorder(inveInMoney);
		total.setTotalUnenterinRefundorder(inveOutMoney);
		total.setTotalUnpaySettleorder(paymoney);
		total.setTotalUnpaySettleorderCheck(settorcheck);

		LogUtils.info(
				log,
				"statTHIRDSELLER_JD  %s --> [all store in %s] + [all store out %s ] + [all Unpay %s] ",
				user.getUsername(), inveInMoney, inveOutMoney, paymoney);

	}

	@Override
	public void statSUPPLIER_TMALL(TbSlPlatformUser user,
			TbCatchdataStrategy ca, TbSlLoanStatTotal total) {
		String time = TimeUtils.getCurDate();

		long inveInMoney = inventoryService
				.queryInventoryInMoneyByRowCreateTime(user.getId(), time, time);

		long inveOutMoney = inventoryService
				.queryInventoryOutMoneyByRowCreateTime(user.getId(), time, time);

		String LastcreateDate = paymentService.getLastcreateDate(user.getId(),
				TbSlSupplyPayment.WAITPAY);

		if (CommonUtils.isEmpty(LastcreateDate)) {
			LastcreateDate = paymentService.getLastcreateDate(user.getId(),
					TbSlSupplyPayment.COMPLETEPAY);
		}

		long unpaySettleorder = paymentService
				.querySupplysettlementMoney(user.getId(), null, null, time,
						time, TbSlSupplyPayment.WAITPAY);

		long settorcheck = paymentService.querySupplysettlementMoney(
				user.getId(), null, null, time, time,
				TbSlSupplyPayment.CHECKEDPAY);

		// long settorcheck =
		// paymentService.querySupplysettlementMoney(user.getId(),TbSlSupplyPayment.CHECKEDPAY);

		total.setTotalUnsettleInstoreorder(inveInMoney);
		total.setTotalUnenterinRefundorder(inveOutMoney);
		total.setTotalUnpaySettleorder(unpaySettleorder);
		total.setTotalUnpaySettleorderCheck(settorcheck);

		LogUtils.info(
				log,
				"statSUPPLIER_SFBEST  %s --> [ store in time:%s ] + [store out time:%s] + [Unpay time:%s] +[checkedpay time:%s ]",
				user.getUsername(), time, time, time, time);

	}

	@Override
	public void statSUPPLIER_WOMAI(TbSlPlatformUser user,
			TbCatchdataStrategy ca, TbSlLoanStatTotal total) {

		statSUPPLIER_SFBEST(user, ca, total);

	}

	@Override
	public void statSUPPLIER_JD(TbSlPlatformUser user, TbCatchdataStrategy ca,
			TbSlLoanStatTotal total) {
		String time = TimeUtils.getCurDate();
		long paymoney = paymentService
				.querySupplysettlementMoneyByRowCreateTime(user.getId(), time,
						time);

		total.setTotalUnpaySettleorder(paymoney);

	}

}
